﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace tab2sql
{
    class informix
    {


        /// <summary>
        /// Removes some (but definitely not all) of the propietary aspects 
        /// of a SQL Server statement and gives a generally Informix SQL compliant version. 
        /// This isn't very smart at present. (Dec-2008)
        /// </summary>
        /// <param name="inputString"></param>
        /// <returns></returns>
        public static string makeInformixSafe(string inputString)
        {
            string resultString = inputString.Replace("[", String.Empty);
            resultString = dataTypes(resultString);
            resultString = changeDateFormats(resultString);
            resultString = resultString.Replace("]", String.Empty);
            resultString = resultString.Replace(";", ";" + Environment.NewLine + "GO" + Environment.NewLine);
            resultString = resultString.TrimStart();

            return resultString;
        }

        private static string dataTypes(string input)
        {
            string pattern = @"CREATE\sTABLE\s#";
            string replace = @"CREATE TEMP TABLE ";
            string s = Regex.Replace(input, pattern, replace);

            pattern = @"DATETIME";
            replace = @"DATE";

            s = Regex.Replace(s, pattern, replace);

            pattern = @"INSERT INTO #";
            replace = @"INSERT INTO ";

            s = Regex.Replace(s, pattern, replace);

            pattern = @"BEGIN TRY(.*)END CATCH";
            replace = String.Empty;

            s = Regex.Replace(s, pattern, replace, RegexOptions.Singleline);

            pattern = @"SET NOCOUNT ON;";
            replace = String.Empty;
            s = Regex.Replace(s, pattern, replace);

            pattern = @"FROM #";
            replace = @"FROM  ";
            s = Regex.Replace(s, pattern, replace);

            pattern = @"TOP \d+";
            replace = String.Empty;
            s = Regex.Replace(s, pattern, replace);

            pattern = @"\n\n";
            replace = @"\n";
            s = Regex.Replace(s, pattern, replace);
            return s;



        }

        // this is very crude
        private static string changeDateFormats(string input)
        {
            string YYYYMMDD = @"([1][0-9]{3}|[2][0-9]{3})-([1][0-2]|[0][1-9]|[1-9])-([3][0-1]|[2][0-9]|[1][0-9]|[0][1-9])";

            string replace = @"$2/$3/$1";
            string s = Regex.Replace(input, YYYYMMDD, replace);
            return s;
        }




    }
}
